<?php
class UserService extends BaseService
{

    private $redisObj;
    static private $_instance = NULL;

    private function  __construct()
    {
        $this->redisObj = Config::getRedisClient();
    }

    private function  __clone()
    {
    }

    static public function getInstance()
    {
        if (is_null(self::$_instance) || !isset(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    //stage set for all user
    public function genStageKey($stage)
    {
        return "game:shooter:" . $stage;
    }

    public function setUserStageScore($stage, $device, $score)
    {
        $key = $this->genStageKey($stage);
        $this->redisObj->zadd($key, $score, $device);
    }

    public function getUserStageScoreCount($stage)
    {
        $key = $this->genStageKey($stage);
        if ($this->redisObj->exists($key)) {
            return $this->redisObj->zcard($key);
        } else {
            return 0;
        }
    }

    //level set for all user
    public function genLevelStageKey($stage)
    {
        return "game:shooter:level:" . $stage;
    }

    public function setUserStageLevel($stage, $device, $level)
    {
        $key = $this->genLevelStageKey($stage);
        $this->redisObj->hset($key, $device, (strval($level)));
    }

    public function getTemp($stage)
    {
        $key = $this->genLevelStageKey($stage);
        return $this->redisObj->hkeys($key);
    }

    public function getUserStageLevel($device,$stage)
    {
        $key = $this->genLevelStageKey($stage);
        if ($this->redisObj->hexists($key,$device)) {
            return (int)$this->redisObj->hget($key,$device);
        } else {
            return 1;
        }
    }



    //score set for user rank
    public function  genUsersRankKey()
    {
        return "game:users:rank";
    }

    public function setUserRank($device, $score)
    {
        $key = $this->genUsersRankKey();
        $this->redisObj->zadd($key, $score, $device);
    }

    public function getUserRank($offset = 0, $count = 10)
    {
        $key = $this->genUsersRankKey();
        return $this->redisObj->zrevrange($key, $offset, $count - 1);
    }

    public function getUserLevel($device, $rank)
    {
        $key = $this->genUsersRankKey();
        $count = $this->redisObj->zcard($key);
        $inx = $this->redisObj->zrank($key, $device);
        if ($inx / $count > 3 / 4) {
            return 4;
        } elseif ($inx / $count > 2 / 4) {
            return 3;
        } elseif ($inx / $count > 1 / 4) {
            return 2;
        } else {
            return 1;
        }
    }

    public function getUserStageLevelOld($deviceCode, $stageKey)
    {
        $count = $this->getUserStageScoreCount($stageKey);
        $inx = $this->getUserInxFromStageScore($stageKey, $deviceCode);
        if ($count >= 4) {
            if ($inx / $count > 3 / 4) {
                return 4;
            } elseif ($inx / $count > 2 / 4) {
                return 3;
            } elseif ($inx / $count > 1 / 4) {
                return 2;
            } else {
                return 1;
            }
        } else {
            return ($inx - $count + 4 + 1);
        }
    }

    public function getStageLevelAroundFriend($u, $uList)
    {
        $count = count($uList);
        $inx = $count - (array_keys($uList, $u, true)[0]);
        if ($count >= 4) {
            if ($inx / $count > 3 / 4) {
                return 4;
            } elseif ($inx / $count > 2 / 4) {
                return 3;
            } elseif ($inx / $count > 1 / 4) {
                return 2;
            } else {
                return 1;
            }
        } else {
            return (4 - (array_keys($uList, $u, true)[0]));
        }
    }

    //token
    public function genDeviceTokenKey()
    {
        return "game:DejaToken";
    }

    public function setDeviceToken($device, $token)
    {
        $key = $this->genDeviceTokenKey();
        $this->redisObj->hset($key, $device, $token);
    }

    public function getDeviceToken($device)
    {
        $key = $this->genDeviceTokenKey();
        return $this->redisObj->hget($key, $device);
    }

    //refresh token
    public function genDeviceRefreshTokenKey()
    {
        return "game:DejaRefreshToken";
    }

    public function setDeviceRefreshToken($device, $token)
    {
        $key = $this->genDeviceRefreshTokenKey();
        $this->redisObj->hset($key, $device, $token);
    }

    public function getDeviceRefreshToken($device)
    {
        $key = $this->genDeviceRefreshTokenKey();
        return $this->redisObj->hget($key, $device);
    }

    //avatar cache
    public function genAvatarKey($dejaId)
    {
        return "game:avatar:" . $dejaId;
    }

    public function setAvatarKey($dejaId, $val)
    {
        $key = $this->genAvatarKey($dejaId);
        $this->redisObj->set($dejaId, $val);
    }

    public function getAvatar($dejaId)
    {
        $key = $this->genAvatarKey($dejaId);
        if ($this->redisObj->exists($key)) {
            return $this->redisObj->get($key);
        } else {
            return null;
        }
    }


    //token cache
    public function genTokenKey($token)
    {
        return "game:token:" . $token;
    }

    public function addToken($randomNum, $device)
    {
        $token = (((int)$randomNum + 365) * 366);
        $token = substr((string)$token, 0, 6);
        $token = md5($token . $device);
        $key = $this->genTokenKey($token);
        $this->redisObj->set($key, $device);
        $this->redisObj->expire($key, 100 * 24 * 60 * 60);
    }

    public function isTokenExists($token)
    {
        $key = $this->genTokenKey($token);
        $result = $this->redisObj->exists($key);
        if ($result) {
            $this->redisObj->expire($key, 3 * 24 * 60 * 60);
        }
        return $result;
    }


    //Deja id to devicetail
    public function genDejaDeviceKey($dejaId)
    {
        return "game:DejaIdToDevice:" . $dejaId;
    }

    public function addDejaDeviceKey($dejaId, $device)
    {
        $key = $this->genDejaDeviceKey($dejaId);
        $this->redisObj->set($key, $device);
    }

    public function updateDejaDeviceKey($dejaId, $device)
    {
        $key = $this->genDejaDeviceKey($dejaId);
        $this->redisObj->set($key, $device);
    }

    public function getDevice($dejaId)
    {
        $key = $this->genDejaDeviceKey($dejaId);
        if ($this->redisObj->exists($key)) {
            return $this->redisObj->get($key);
        } else {
            return null;
        }
    }

    //Deja id to deja model
    public function genDejaUKey($dejaId)
    {
        return "game:DejaId:" . $dejaId;
    }

    public function addDejaUKey($dejaId, $dejaModel)
    {
        $key = $this->genDejaUKey($dejaId);
        if (!$this->redisObj->exists($key)) {
            $this->redisObj->set($key, $dejaModel);
        }
        $this->redisObj->expire($key, 7 * 60 * 60);
    }

    public function updateDejaUKey($dejaId, $dejaModel)
    {
        $key = $this->genDejaUKey($dejaId);
        $this->redisObj->set($key, $dejaModel);
        $this->redisObj->expire($key, 3 * 24 * 60 * 60);
    }

    public function getCacheDejaM($dejaId)
    {
        $key = $this->genDejaUKey($dejaId);
        parent::llog($key, "User.Cache");
        if ($this->redisObj->exists($key)) {
            return json_decode($this->redisObj->get($key));
        } else {
            return null;
        }
    }

    //Device to game user model
    public function genDeviceUKey($device)
    {
        return "game:DeviceU:" . $device;
    }

    public function addDeviceUKey($device, $user)
    {
        $key = $this->genDeviceUKey($device);
        if (!$this->redisObj->exists($key)) {
            $this->redisObj->set($key, $user);
        }
        $this->redisObj->expire($key, 7 * 24 * 60 * 60);
    }

    public function updateDeviceUKey($device, $user)
    {
        $key = $this->genDeviceUKey($device);
        $this->redisObj->set($key, $user);
        $this->redisObj->expire($key, 7 * 24 * 60 * 60);
    }

    public function getCacheU($device)
    {
        $key = $this->genDeviceUKey($device);
        parent::llog($key, "User.Cache");
        if ($this->redisObj->exists($key)) {
            $this->redisObj->expire($key, 7 * 24 * 60 * 60);
            return json_decode($this->redisObj->get($key));
        } else {
            return null;
        }
    }

    //Not User model
    public function getUserByDevice($device)
    {
        $result = null;
        $result = $this->getCacheU($device);
        if (!isset($result)) {
            $result = User::model()->find('device=:device', array(':device' => $device));
            if (isset($result)) {
                $this->addDeviceUKey($device, json_encode($result->attributes));
            }

        }
        return $result;
    }

    //other functions
    //User model
    public function findByDevice($device)
    {
        $result = null;
        $User = $this->getCacheU($device);
        if (isset($User)) {
            $result = User::model()->findByPk($User->id);
        } else {
            $result = User::model()->find('device=:device', array(':device' => $device));
        }
        return $result;
    }

    public function getDefaultDejaModel($dejaId, $device, $faceId = "", $size = 128)
    {
        $result = null;
        //$dejaData = $this->getCacheDejaM($dejaId);
        if (!isset($dejaData)) {
            parent::llog("from api", "UserService.getDejaModel.Returndata");

            $getProfilesUrl = trim(Config::$public_apis['getProfiles'], '/');
            $postData = array("userId" => $dejaId, "user_ids" => array($dejaId));
            parent::llog(arrayToKV($postData), "UserService.getDejaModel.Deja.Postdata");
            $resStr = UserService::getInstance()->requestDejaApi($getProfilesUrl, $postData, Config::$defaultDevice);
            parent::llog(json_encode($resStr), "UserService.getDejaModel.Returndata");

            $getAvatarUrl = trim(Config::$public_apis['getAvatar'], '/');
            $postDataT = array("faceId" => $faceId, "size" => $size, "smiley_standard" => 1, "include_avatar" => 1);
            parent::llog(arrayToKV($postDataT), "UserService.getDejaModel.Deja.Postdata");
            parent::llog($getAvatarUrl, "UserService.getDejaModel.Deja.Url");
            $resStrT = UserService::getInstance()->requestDejaApi($getAvatarUrl, $postDataT, Config::$defaultDevice);
            parent::llog(json_encode($resStrT), "UserService.getDejaModel.Returndata");
            if (isset($resStr)) {
                $result = new DejaModel();
                if (isset($resStr->profiles[0])) {
                    $result->id = $resStr->profiles[0]->userId;;
                    $device = $this->getDevice($result->id);
                    $result->device = $device;
                    $result->name = $resStr->profiles[0]->name;
                    $result->tagline = $resStr->profiles[0]->tagline;
                    $result->gender = $resStr->profiles[0]->gender;
                    $result->profilePic = $resStr->profiles[0]->avatar;
                } else {
                    $result->id = -1;
                    $result->device = $device;
                    $u = UserService::getInstance()->getUserByDevice($device);
                    $result->name = $u->user_name;
                    $result->tagline = "";
                    $result->gender = 1;
                }
            }
            if (isset($result)) {
                $this->updateDejaUKey($dejaId, json_encode($result));
            }
            if (!empty($resStrT) && isset($result)) {
                $result->faceId = $resStrT->faceId;
                if ($result->faceId == $faceId) {
                    $result->isAvaUpdated = 0;
                } else {
                    $result->isAvaUpdated = 1;
                }
                parent::llog(json_encode($result), "UserService.getDejaModel.temp");
                $result->avatar = $resStrT->avatar;
                $result->avatar_head = str_ireplace("normal", "headonly", $resStrT->avatar);
                $this->updateDejaUKey($dejaId, json_encode($result));
                $result->smiley = $resStrT->smiley;
            }
            if (isset($result) && $size != 128) {
                $avUrl = $result->avatar;
                $avHeadUrl = $result->avatar_head;
                $avPos = strpos($avUrl, "/avatar/");
                $stylePos = strpos($avUrl, "/normal/");
                $styleHeadPos = strpos($avHeadUrl, "/headonly/");
                $fUrl = substr($avUrl, 0, $avPos + 8);
                $eUrl = substr($avUrl, $stylePos);
                $eHeadUrl = substr($avHeadUrl, $styleHeadPos);
                $newUrl = $fUrl . $size . $eUrl;
                $newHeadUrl = $fUrl . $size . $eHeadUrl;
                $result->avatar = $newUrl;
                $result->avatar_head = $newHeadUrl;
                if ($size == 64) {
                    $result->profilePic = str_ireplace("__", "80", $result->profilePic);
                } else if ($size == 128) {
                    $result->profilePic = str_ireplace("__", "120", $result->profilePic);
                } else if ($size == 256) {
                    $result->profilePic = str_ireplace("__", "240", $result->profilePic);
                } else {
                    $result->profilePic = str_ireplace("__", "360", $result->profilePic);
                }
            }
            if (isset($result) && empty($result->profilePic)) {
                $result->profilePic = $result->avatar;
            }
        } else {
            parent::llog("from cache", "UserService.getDejaModel.ReturnData");
            $result = $dejaData;
        }
        return $result;
    }


    public function getDejaModel($dejaId, $device, $faceId = "", $size = 128)
    {
        $result = null;
        //$dejaData = $this->getCacheDejaM($dejaId);
        if (!isset($dejaData)) {
            parent::llog("from api", "UserService.getDejaModel.Returndata");

            $getProfilesUrl = trim(Config::$public_apis['getProfiles'], '/');
            $postData = array("userId" => $dejaId, "user_ids" => array($dejaId));
            parent::llog(arrayToKV($postData), "UserService.getDejaModel.Deja.Postdata");
            $resStr = UserService::getInstance()->requestDejaApi($getProfilesUrl, $postData, $device);
            parent::llog(json_encode($resStr), "UserService.getDejaModel.Returndata");

            $getAvatarUrl = trim(Config::$public_apis['getAvatar'], '/');
            $postDataT = array("faceId" => $faceId, "size" => $size, "smiley_standard" => 0, "include_avatar" => 1, "smileys" => array("discreetlaugh", "pitiful"));
            parent::llog(arrayToKV($postDataT), "UserService.getDejaModel.Deja.Postdata");
            parent::llog($getAvatarUrl, "UserService.getDejaModel.Deja.Url");
            $resStrT = UserService::getInstance()->requestDejaApi($getAvatarUrl, $postDataT, $device);
            parent::llog(json_encode($resStrT), "UserService.getDejaModel.Returndata");
            if (isset($resStr)) {
                $result = new DejaModel();
                $result->id = $resStr->profiles[0]->userId;
                $device = $this->getDevice($result->id);
                $result->device = $device;
                $result->name = $resStr->profiles[0]->name;
                $result->tagline = $resStr->profiles[0]->tagline;
                $result->gender = $resStr->profiles[0]->gender;
                $result->profilePic = $resStr->profiles[0]->avatar;
            }
            if (isset($result)) {
                $this->updateDejaUKey($dejaId, json_encode($result));
            }
            if (!empty($resStrT) && isset($result)) {
                $result->faceId = $resStrT->faceId;
                if ($result->faceId == $faceId) {
                    $result->isAvaUpdated = 0;
                } else {
                    $result->isAvaUpdated = 1;
                }
                parent::llog(json_encode($result), "UserService.getDejaModel.temp");
                $result->avatar = $resStrT->avatar;
                $result->avatar_head = str_ireplace("normal", "headonly", $resStrT->avatar);
                $this->updateDejaUKey($dejaId, json_encode($result));
                $result->smiley = $resStrT->smiley;
//                if(isset($result->smiley))
//                {
//                    foreach($result->smiley as $smileyName=>$vval)
//                    {
//                        $tName = $smileyName."Count";
//                        var_dump(count($vval));
//                        $result->smiley->$tName = count($vval);
//                    }
//                }
            }
            if (isset($result) && $size != 128) {
                $avUrl = $result->avatar;
                $avHeadUrl = $result->avatar_head;
                $avPos = strpos($avUrl, "/avatar/");
                $stylePos = strpos($avUrl, "/normal/");
                $styleHeadPos = strpos($avHeadUrl, "/headonly/");
                $fUrl = substr($avUrl, 0, $avPos + 8);
                $eUrl = substr($avUrl, $stylePos);
                $eHeadUrl = substr($avHeadUrl, $styleHeadPos);
                $newUrl = $fUrl . $size . $eUrl;
                $newHeadUrl = $fUrl . $size . $eHeadUrl;
                $result->avatar = $newUrl;
                $result->avatar_head = $newHeadUrl;
                if ($size == 64) {
                    $result->profilePic = str_ireplace("__", "80", $result->profilePic);
                } else if ($size == 128) {
                    $result->profilePic = str_ireplace("__", "120", $result->profilePic);
                } else if ($size == 256) {
                    $result->profilePic = str_ireplace("__", "240", $result->profilePic);
                } else {
                    $result->profilePic = str_ireplace("__", "360", $result->profilePic);
                }
            }


        } else {
            parent::llog("from cache", "UserService.getDejaModel.ReturnData");
            $result = $dejaData;
        }
        return $result;
    }

    public function getFriendDejaModel($dejaId, $device, $size = 128)
    {
        $result = null;
        $dejaData = $this->getCacheDejaM($dejaId);
        if (!isset($dejaData)) {
            parent::llog("from api", "UserService.getDejaModel.Returndata");

            $getProfilesUrl = trim(Config::$public_apis['getProfiles'], '/');
            $postData = array("user_ids" => array($dejaId));
            parent::llog(arrayToKV($postData), "UserService.getDejaModel.Deja.Postdata");
            $resStr = UserService::getInstance()->requestDejaApi($getProfilesUrl, $postData, $device);
            parent::llog(json_encode($resStr), "UserService.getDejaModel.Returndata");

            $getAvatarUrl = trim(Config::$public_apis['getAvatar'], '/');
            $postDataT = array("faceId" => "", "size" => $size, "smiley_standard" => 1, "include_avatar" => 1);
            parent::llog(arrayToKV($postDataT), "UserService.getDejaModel.Deja.Postdata");
            $resStrT = UserService::getInstance()->requestDejaApi($getAvatarUrl, $postDataT, $device);
            parent::llog(json_encode($resStrT), "UserService.getDejaModel.Returndata");
            if (isset($resStr)) {
                $result = new DejaModel();
                $result->isAvaUpdated = true;
                $result->id = $resStr->profiles[0]->userId;
                $result->name = $resStr->profiles[0]->name;
                $result->tagline = $resStr->profiles[0]->tagline;
                $result->gender = $resStr->profiles[0]->gender;
                $result->profilePic = $resStr->profiles[0]->avatar;
            }
            if (isset($result)) {
                $this->updateDejaUKey($dejaId, json_encode($result));
            }
            if (!empty($resStrT) && isset($result)) {
                $result->faceId = $resStrT->faceId;
                $result->avatar = $resStrT->avatar;
                $result->avatar_head = str_ireplace("normal", "headonly", $resStrT->avatar);
                $this->updateDejaUKey($dejaId, json_encode($result));
                //$result->smiley = $resStrT->smiley;
            }

        } else {
            parent::llog("from cache", "UserService.getDejaModel.ReturnData");
            $result = $dejaData;
        }
        if (isset($result)) {
            $avUrl = $result->avatar;
            $avHeadUrl = $result->avatar_head;
            $avPos = strpos($avUrl, "/avatar/");
            $stylePos = strpos($avUrl, "/normal/");
            $styleHeadPos = strpos($avHeadUrl, "/headonly/");
            $fUrl = substr($avUrl, 0, $avPos + 8);
            $eUrl = substr($avUrl, $stylePos);
            $eHeadUrl = substr($avHeadUrl, $styleHeadPos);
            $newUrl = $fUrl . $size . $eUrl;
            $newHeadUrl = $fUrl . $size . $eHeadUrl;
            $result->avatar = $newUrl;
            $result->avatar_head = $newHeadUrl;
            $unknownPic = false;
            if (isset($result->profilePic) && strpos($result->profilePic, "unknown") > 0) {
                $unknownPic = true;
            }
            if ($size == 64) {
                if ($unknownPic) {
                    $result->profilePic = "http://api.game.shooter.mozat.com/g_shooter/data/avatar/unknown80.png";
                } else {
                    $result->profilePic = str_ireplace("__", "80", $result->profilePic);
                }
            } else if ($size == 128) {
                if ($unknownPic) {
                    $result->profilePic = "http://api.game.shooter.mozat.com/g_shooter/data/avatar/unknown120.png";
                } else {
                    $result->profilePic = str_ireplace("__", "120", $result->profilePic);
                }
            } else if ($size == 256) {
                if ($unknownPic) {
                    $result->profilePic = "http://api.game.shooter.mozat.com/g_shooter/data/avatar/unknown240.png";
                } else {
                    $result->profilePic = str_ireplace("__", "240", $result->profilePic);
                }
            } else {
                if ($unknownPic) {
                    $result->profilePic = "http://api.game.shooter.mozat.com/g_shooter/data/avatar/unknown360.png";
                } else {
                    $result->profilePic = str_ireplace("__", "360", $result->profilePic);
                }
            }

        }
        return $result;
    }


//    public function requestDejaData($uid, $requesIds)
//    {
//        $sendSMSUrl = trim(Config::$public_apis['getProfiles'], '/');
//        $postdata = json_encode(array("userId" => $uid, "requestIds" => $requesIds));
//        parent::llog($postdata, "UserService.requestDejaData.Deja.Postdata");
//        $resStr = Trans::sendUrlPostJson($sendSMSUrl, $postdata);
//        parent::llog($resStr, "UserService.requestDejaData.Postdata");
//        return $resStr;
//    }

    public function getFriendIds($dejaId, $device)
    {
        $result = array();
        $sendSMSUrl = trim(Config::$public_apis['getFriends'], '/');
        parent::llog($sendSMSUrl, "UserService.getFriends.Deja.GetUrl");
        $resStr = UserService::getInstance()->requestDejaApi($sendSMSUrl, array(), $device);
        parent::llog(json_encode($resStr), "UserService.getFriends.Deja.ReturnData");
        if (isset($resStr)) {
            if (isset($resStr->error)) {
                return array();
            } else {
                $result = $resStr->friends;
            }
        }
        return $result;
    }

    //have deja info
    public function getFriendsInGamesFromDeja($ids, $deviceT, $size)
    {
        $result = array();
        if (isset($ids) && is_array($ids)) {
            //$devices = UserService::getInstance()->getUserRank(0, 0);
            foreach ($ids as $value) {
                $key = $this->genDejaDeviceKey($value);
                if ($this->redisObj->exists($key)) {
                    $deviceF = $this->getDevice($value);
                    $temp = $this->getFriendDejaModel($value, $deviceF, $size);
                    if (isset($temp)) {
                        $device = $this->getDevice($value);
                        $temp->isFriend = true;
                        $temp->device = $device;
                        unset($temp->tagline);
                        unset($temp->faceId);
                        unset($temp->isAvaUpdated);
                        unset($temp->smiley);
                        $g_user = $this->getUserByDevice($device);
                        if (isset($g_user) && isset($g_user->rank)) {
                            $temp->rank = (int)$g_user->rank;
                        } else {
                            $temp->rank = 0;
                        }
                        $device = $this->getDevice($value);
                        $level = $this->getUserLevel($device, $temp->rank);
                        if (isset($level)) {
                            $temp->level = $level;
                        } else {
                            $temp->level = 0;
                        }
                        array_push($result, $temp);
                    }
                }
            }
        }
        return $result;
    }

    public function getFriendsInfoWithStage($ids, $deviceCode, $size)
    {
        $result = array();
        if (isset($ids) && is_array($ids)) {
            //$devices = UserService::getInstance()->getUserRank(0, 0);
            foreach ($ids as $value) {
                $key = $this->genDejaDeviceKey($value);
                if ($this->redisObj->exists($key)) {
                    $temp = new stdClass();
                    $temp->id = (int)$value;
                    $temp->device = $this->getDevice($value);
                    $g_user = $this->getUserByDevice($temp->device);
                    if (isset($g_user)) {
                        $temp->stages = $g_user->higest_score;
                    }
                    array_push($result, $temp);

//                    $temp = $this->getFriendDejaModel($value, $deviceCode, $size);
//                    if (isset($temp)) {
//                        $device = $this->getDevice($value);
//                        $temp->isFriend = true;
//                        $temp->device = $device;
//                        $g_user = $this->getUserByDevice($device);
//                        if (isset($g_user) && isset($g_user->rank)) {
//                            $temp->rank = (int)$g_user->rank;
//                        } else {
//                            $temp->rank = 0;
//                        }
//                        $device = $this->getDevice($value);
//                        $level = $this->getUserLevel($device, $temp->rank);
//                        if (isset($level)) {
//                            $temp->level = $level;
//                        } else {
//                            $temp->level = 0;
//                        }
//                        $temp->stages = $g_user->higest_score;
//                        unset($temp->tagline);
//                        unset($temp->faceId);
//                        unset($temp->isAvaUpdated);
//                        unset($temp->smiley);
//                        unset($temp->rank);
//                        unset($temp->level);
//                        unset($temp->isFriend);
//                        unset($temp->name);
//                        unset($temp->gender);
//                        unset($temp->avatar);
//                        unset($temp->avatar_head);
//                        unset($temp->profilePic);
//                        array_push($result, $temp);
//                    }
                }
            }
        }
        return $result;
    }


    //do not have deja info
    public function getUsersRankFromDevices($devices, $size, $friends = [])
    {
        $result = array();
        foreach ($devices as $device) {
            $u = $this->getUserByDevice($device);
            if (isset($u)) {
                $temp = null;
                if (isset($u->deja_id) && ((int)$u->deja_id) > 0) {
                    $temp = $this->getFriendDejaModel($u->deja_id, $size);
                    if (isset($temp)) {
                        unset($temp->tagline);
                        $temp->device = $device;
                        if (isset($u->rank)) {
                            $temp->rank = (int)$u->rank;
                        } else {
                            $temp->rank = 0;
                        }
                        $level = $this->getUserLevel($device, $temp->rank);
                        if (isset($level)) {
                            $temp->level = $level;
                        } else {
                            $temp->level = 0;
                        }
                    } else {
                        $temp = new DejaModel();
                        $temp->device = $device;
                        $temp->isAvaUpdated = true;
                        $temp->id = -1;
                        $temp->avatar = Config::$default_avatar_men[array_rand(Config::$default_avatar_men, 1)];
                        $temp->avatar_head = Config::$default_avatar_men_head[array_rand(Config::$default_avatar_men_head, 1)];
                        if (isset($u->rank)) {
                            $temp->rank = (int)$u->rank;
                        } else {
                            $temp->rank = 0;
                        }
                        $level = $this->getUserLevel($device, $temp->rank);
                        if (isset($level)) {
                            $temp->level = $level;
                        } else {
                            $temp->level = 0;
                        }
                    }
                } else {
                    $temp = new DejaModel();
                    $temp->device = $device;
                    $temp->isAvaUpdated = true;
                    $temp->id = -1;
                    $temp->name = $u->user_name;
                    $temp->avatar = Config::$default_avatar_men[array_rand(Config::$default_avatar_men, 1)];
                    $temp->avatar_head = Config::$default_avatar_men_head[array_rand(Config::$default_avatar_men_head, 1)];
                    if (isset($u->rank)) {
                        $temp->rank = (int)$u->rank;
                    } else {
                        $temp->rank = 0;
                    }
                    $level = $this->getUserLevel($device, $temp->rank);
                    if (isset($level)) {
                        $temp->level = $level;
                    } else {
                        $temp->level = 0;
                    }
                }
                if (isset($temp)) {
                    if (in_array($temp->id, $friends)) {
                        $temp->isFriend = true;
                    } else {
                        $temp->isFriend = false;
                    }
                    if ($size != 128) {
                        $avUrl = $temp->avatar;
                        $avHeadUrl = $temp->avatar_head;
                        $avPos = strpos($avUrl, "/avatar/");
                        $stylePos = strpos($avUrl, "/normal/");
                        $styleHeadPos = strpos($avHeadUrl, "/headonly/");
                        $fUrl = substr($avUrl, 0, $avPos + 8);
                        $eUrl = substr($avUrl, $stylePos);
                        $eHeadUrl = substr($avHeadUrl, $styleHeadPos);
                        $newUrl = $fUrl . $size . $eUrl;
                        $newHeadUrl = $fUrl . $size . $eHeadUrl;
                        $temp->avatar = $newUrl;
                        $temp->avatar_head = $newHeadUrl;
                    }
                    array_push($result, $temp);
                }
            }
        }
        return $result;
    }


    public function requestDejaApi($url, $data, $device)
    {
        $token = $this->getDeviceToken($device);
        if (!isset($token)) {
            throw new CHttpException(401, 'refresh token fail');
        }
        $data["access_token"] = $token;
        $postData = arrayToKV($data);
        $resStr = Trans::sendUrlPostKV($url, $postData);
        parent::llog($postData, "UserService.API.post");
        parent::llog($url, "UserService.API.url");
        parent::llog($resStr, "UserService.API.return");
        $resStr = json_decode($resStr);
        if (isset($resStr->error) && $resStr->error == "invalid_token") {
            $refreshToken = $this->getDeviceRefreshToken($device);
            $getTokenUrl = trim(Config::$public_apis['gettoken'], '/');
            $postDataT = arrayToKV(array("grant_type" => "refresh_token", "client_id" => Config::$client_id, "client_secret" => Config::$client_secret, "refresh_token" => $refreshToken));;
            $resStrT = Trans::sendUrlPostKV($getTokenUrl, $postDataT);
//            var_dump($postDataT);
//            var_dump($resStrT);
//            return null;
            if (!empty($resStrT)) {
                $resStrT = json_decode($resStrT);
                if (isset($resStrT->error)) {
                    throw new CHttpException(401, 'refresh token fail');
                } else {
                    $access_tokenV = $resStrT->access_token;
                    $refresh_tokenV = $resStrT->refresh_token;
                    UserService::getInstance()->setDeviceToken($device, $access_tokenV);
                    UserService::getInstance()->setDeviceRefreshToken($device, $refresh_tokenV);
                    $data["access_token"] = $access_tokenV;
                    $postDataV = arrayToKV($data);
                    $resStr = Trans::sendUrlPostKV($url, $postDataV);
                    return json_decode($resStr);
                }
            } else {
                throw new CHttpException(401, 'refresh token fail');
            }
        }
        return $resStr;
    }

    public function pushDejaMessage($fromId, $toId, $device, $message)
    {
        $result = false;
        $postData = array("action_url" => "http://baidu.com", "text" => $message, "client_id" => Config::$client_id, "from_id" => $fromId, "to_id" => $toId);
        parent::llog(arrayToKV($postData), "UserService.pushDejaMessage.Post");
        $result = UserService::getInstance()->requestDejaApi(Config::$public_apis["pushMessage"], $postData, $device);
        parent::llog(json_encode($result), "UserService.pushDejaMessage.Return");
        if (isset($result)) {
            if (isset($result->delivered) && $result->delivered == 0) {
                $result = true;
            }
        }

        return $result;
    }


}